"""
公告公示API路由
"""
from datetime import datetime
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func, or_, and_
import math

from app.database import get_db
from app.models.announcement import Announcement
from app.schemas.announcement import (
    AnnouncementCreate, 
    AnnouncementUpdate, 
    AnnouncementResponse, 
    AnnouncementListResponse,
    AnnouncementStatusUpdate,
    AnnouncementStatsResponse
)
from app.dependencies import get_current_user
from app.models.user import User

router = APIRouter(prefix="/api/announcements", tags=["announcements"])

@router.get("", response_model=AnnouncementListResponse)
def get_announcements(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    category: Optional[str] = Query(None, description="分类筛选"),
    published_only: bool = Query(True, description="仅显示已发布"),
    db: Session = Depends(get_db)
):
    """获取公告列表"""
    query = db.query(Announcement)
    
    # 筛选条件
    if published_only:
        query = query.filter(Announcement.is_published == True)
    
    if keyword:
        query = query.filter(
            or_(
                Announcement.title.contains(keyword),
                Announcement.excerpt.contains(keyword),
                Announcement.content.contains(keyword)
            )
        )
    
    if category:
        query = query.filter(Announcement.category == category)
    
    # 排序
    query = query.order_by(Announcement.created_at.desc())
    
    # 分页
    total = query.count()
    pages = math.ceil(total / size)
    offset = (page - 1) * size
    
    announcements = query.offset(offset).limit(size).all()
    
    return AnnouncementListResponse(
        items=announcements,
        total=total,
        page=page,
        size=size,
        pages=pages
    )

@router.get("/stats", response_model=AnnouncementStatsResponse)
def get_announcement_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取公告统计信息"""
    total_announcements = db.query(Announcement).count()
    published_announcements = db.query(Announcement).filter(Announcement.is_published == True).count()
    draft_announcements = total_announcements - published_announcements
    total_views = db.query(func.sum(Announcement.view_count)).scalar() or 0
    
    return AnnouncementStatsResponse(
        total_announcements=total_announcements,
        published_announcements=published_announcements,
        draft_announcements=draft_announcements,
        total_views=total_views
    )

@router.get("/{announcement_id}", response_model=AnnouncementResponse)
def get_announcement(
    announcement_id: int,
    db: Session = Depends(get_db)
):
    """获取单个公告详情"""
    announcement = db.query(Announcement).filter(Announcement.id == announcement_id).first()
    if not announcement:
        raise HTTPException(status_code=404, detail="公告不存在")
    
    # 增加浏览次数
    announcement.view_count += 1
    db.commit()
    db.refresh(announcement)
    
    return announcement

@router.post("", response_model=AnnouncementResponse)
def create_announcement(
    announcement_data: AnnouncementCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建公告"""
    announcement = Announcement(**announcement_data.dict())
    
    # 如果是发布状态，设置发布时间
    if announcement.is_published:
        announcement.published_at = datetime.now()
    
    db.add(announcement)
    db.commit()
    db.refresh(announcement)
    
    return announcement

@router.put("/{announcement_id}", response_model=AnnouncementResponse)
def update_announcement(
    announcement_id: int,
    announcement_data: AnnouncementUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新公告"""
    announcement = db.query(Announcement).filter(Announcement.id == announcement_id).first()
    if not announcement:
        raise HTTPException(status_code=404, detail="公告不存在")
    
    # 更新字段
    update_data = announcement_data.dict(exclude_unset=True)
    
    # 如果状态从未发布变为发布，设置发布时间
    if "is_published" in update_data and update_data["is_published"] and not announcement.is_published:
        update_data["published_at"] = datetime.now()
    
    for field, value in update_data.items():
        setattr(announcement, field, value)
    
    db.commit()
    db.refresh(announcement)
    
    return announcement

@router.patch("/{announcement_id}/status", response_model=AnnouncementResponse)
def toggle_announcement_status(
    announcement_id: int,
    status_data: AnnouncementStatusUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """切换公告发布状态"""
    announcement = db.query(Announcement).filter(Announcement.id == announcement_id).first()
    if not announcement:
        raise HTTPException(status_code=404, detail="公告不存在")
    
    announcement.is_published = status_data.is_published
    
    # 如果是发布状态，设置发布时间
    if status_data.is_published and not announcement.published_at:
        announcement.published_at = datetime.now()
    
    db.commit()
    db.refresh(announcement)
    
    return announcement

@router.delete("/{announcement_id}")
def delete_announcement(
    announcement_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除公告"""
    announcement = db.query(Announcement).filter(Announcement.id == announcement_id).first()
    if not announcement:
        raise HTTPException(status_code=404, detail="公告不存在")
    
    db.delete(announcement)
    db.commit()
    
    return {"message": "公告已删除"}

@router.get("/categories/list")
def get_announcement_categories(db: Session = Depends(get_db)):
    """获取公告分类列表"""
    categories = db.query(Announcement.category).distinct().all()
    return [category[0] for category in categories if category[0]]
